define(['jquery','static','text!../template/route.html','text!../template/routeInfo.html','text!../template/routeBatch.html','css!../css/route','common','form'],function($,static,tplRoute,tplRouteInfo,tplRouteBatch){
	let _route = {};
	let address = {};
	let currentPage = 1;
	let currentPoint='';
	let currentAreaId = '';
	let currentAreaType = '';
	let _address = '';
	let tpls = {
		'tplRoute' :_.template(tplRoute),
		'tplRouteInfo' :_.template(tplRouteInfo),
		'tplRouteBatch' :_.template(tplRouteBatch)
	};
	_route.show = function(){
		currentPage = 1;
		$('#contant').html(tpls.tplRoute({message:static.currentUser.role}));
		setRouteTable(0,30);
		var setting = {
	        check: {
	            enable: true,
	            chkStyle: "radio",
	            radioType: 'all',
	            //chkboxType: {"Y" : "s", "N" : "s"}
	        },
	        async: {
	            enable: true,
	            autoParam:["id", "name=n", "level=lv"],
	            otherParam:{"parentId":"320113"},
	            type: "post",
	        },
	        callback:{
	            onCheck:zTreeOnCheck,
	            onClick: function (e, treeId, treeNode, clickFlag) { 
					var zTree = $.fn.zTree.getZTreeObj("treeDemo");
					zTree.checkNode(treeNode, !treeNode.checked, true);
					zTreeOnCheck(e, treeId, treeNode);
				}
	        }
	    };
        setTree("#treeDemo",setting);

        function zTreeOnCheck(event, treeId, treeNode){
	        currentAreaId = treeNode.id;
	        currentAreaType = treeNode.type;
	        $('#areaSel').val(treeNode.name);
	        $('.routeClear').show();
	    }

	    $("#areaClear").click(function(event) {
			currentAreaId = '';
	        currentAreaType = '';
	        $(this).hide();
        	$('#areaSel').val('按管辖区域');
    		setTree("#treeDemo",setting);
		});

		$('.headbutton').click(function(event) {
			let type = $(this).attr('id');
			if(type == "addroute"){
				updateRoute(1);
			}else if (type == "importTable") {
				$('#excelFile').click();
			}else if (type == "exportTable") {
				exportTable();
			}else if (type == "searchRoute") {
				searchRoute();
			}else if (type == "batchUpdate") {
				initBatchUpdate();
			}
		});

		$("#excelFile").bind("change", function() {
	        $("#filePath").attr("value",$("#excelFile").val());
	        layer.confirm('确定导入表格？', {
			    btn: ['确定','取消']
			}, function(){
				layer.closeAll();
				upload();
			}, function(){

			});
	    });

		$('#areaSel').click(function(event) {
		    event.stopPropagation();
			$('.treeBox').toggle();
		});
		$('.treeBox').click(function(event) {
			event.stopPropagation();
		});

		$('body').click(function(event) {
			if($('.treeBox').is(':visible')){
				$('.treeBox').hide();
			}
		});
	}

	function reloadTable(parms){
		currentPage = 1;
		setRouteTable(0,30,parms);
	}

	function setRouteTable(from,count,parms){
		$('#gridRepairTable').datagrid({
	        url: '/xjrest/point/list_point?from='+from+'&count='+count,
	        queryParams:parms?parms:{},
	        width: '100%',
	        method: 'get',
	        border: false,
	        //singleSelect: true,
	        fitColumns:false,
	        scrollbarSize :0,
	        loadMsg: "正在查询,请耐心等待。。。。。。。",
	        columns: [
	            [
	            	{ field: 'pointId', width: "5%", align: 'center',checkbox:true},
	                { field: 'townName', title: '所属街道', width: "10%",align: 'center', formatter: function(value,row){
	                	return `<span title="${value}">${truncate(value,8)}</span>`;
	                }},
	                { field: 'villageName', title: '所属社区', width: "10%", align: 'center', formatter: function(value,row){
	                	return `<span title="${value}">${truncate(value,8)}</span>`;
	                }},
	                { field: 'pointName', title: '建设地址', width: "10%", align: 'center', formatter: function(value,row){
	                	return `<span title="${value}">${truncate(value,8)}</span>`;
	                }},
	                { field: 'manufacturer', title: '器材厂家', width: "10%", align: 'center', formatter: function(value,row){
	                	return `<span title="${value}">${truncate(value,8)}</span>`;
	                }},
	                { field: 'buildTime', title: '建设时间', width: "10%", align: 'center' },
	                { field: 'useTime', title: '使用寿命', width: "5%", align: 'center' },
	                { field: 'equipmentType', title: '器材类型', width: "8%", align: 'center', formatter: function(value,row){
	                	return value==1?'体彩':'自建'
	                }},
	                { field: 'linkman', title: '联系人', width: "10%", align: 'center' },
	                { field: 'linkphone', title: '联系电话', width: "10%", align: 'center' },
	                { field: 'status', title: '操作', width: "15%", align: 'center', formatter: function(value,row){
	                	let data = JSON.stringify(row).replace(/\"/g,"'");
	                		let id = row.pointId;
	                		if(value==2){
	                			return `<div style="display:flex;justify-content: center;align-items: center;">
		                				<input class="routeTableButton buttonBlue" type="button" value="修改" style="margin-right:10px" onclick="updateRoute(3,${data})" />
			                			<input class="routeTableButton buttonBlue" type="button" value="删除" onclick="delRouter('${id}')" />
				                	</div>` 
				            }else{
			                	return `<div style="display:flex;justify-content: center;align-items: center;">
	                				<input class="routeTableButton buttonBlue" type="button" value="待完善" style="margin-right:10px;background: #FFC525;" onclick="updateRoute(3,${data})" />
		                			<input class="routeTableButton buttonBlue" type="button" value="删除" onclick="delRouter('${id}')" />
			                	</div>` 
			                }
		                	
	                }}
	            ]
	        ],
	        loadFilter: function(data){
	            let _data = data.ret.value;
	            let totals = data.ret.total;
	            if (totals == 0) {
	                $("#noRecordMessage").show();
	            } else {
	                $("#noRecordMessage").hide();
	            }
	            if (0 == totals % count) {
	                totalPage = parseInt(totals / count);
	                if (totalPage == 0){
	                     totalPage = 1;
	                }
	            } else {
	                totalPage = parseInt(totals / count) + 1;
	            }
	            $('#pagination').paginations({
	                currentPage: currentPage,
	                totalPage: totalPage,
	                callback: function(current) {
	                    currentPage = current;
	                    current = (current - 1) * count;
	                    setRouteTable(current,count,parms);
	                }
	            });
	            return _data;
	        },
	        onDblClickRow: function(rowIndex, rowData) {
	            updateRoute(2,rowData);
	        }
	    });
	}

	window.delRouter = function(id){
		layer.confirm('确定删除该路径？', {
		  btn: ['确定','取消'] //按钮
		}, function(){
			Ajax("/xjrest/point/point_delete?pointId="+id,delPointBack);
		}, function(){

		});

		function delPointBack(data){
			if(data.ret.success){
				layer.msg('删除成功');
				searchRoute();
			}else{
				layer.msg('删除失败');
			}
		}
	}

	window.updateRoute = function(type,data){
		console.log(data);
		let _data={};
		let pics=[];
		let _html='';
		if(type==2){
			Ajax("/xjrest/task/point_task_image?pointId="+data.pointId,function(result){
				pics = result.ret.value;
				Ajax("/xjrest/area/auth_area?areaType=1",setHtml);
			});
		}else{
			Ajax("/xjrest/area/auth_area?areaType=1",setHtml);
		}
		//Ajax("/xjrest/area/auth_area?areaType=1",setHtml);
		function setHtml(result){
			if(type!=2){
				if(type==3){
					_data=data;
					_data.btnText='确认修改'
				}else{
					_data.btnText='确认添加';
				}
				_data.add=true;
				_data.tree=result.ret.value;
				_html = tpls.tplRouteInfo({message:_data});
			}else{
				_data=data;
				_data.add=false;
				_data.tree=result.ret.value;
				_data.pics=pics;
				_html = tpls.tplRouteInfo({message:_data});
			}
			layer.open({
			  type: 1,
			  title: false,
			  closeBtn: 0,
			  shadeClose: true,
			  skin: 'routeOpen',
			  content: _html
			});
			let child=$('#routeStreet').val();
			Ajax("/xjrest/area/auth_area?areaType=2&townId="+child,function(datas){
				$('#routeVillage').html('');
				let nodes = datas.ret.value;
				$.each(nodes,function(index, el) {
					let html = '';
					if(data){
						html = data.villageId==el.id?`<option value="${el.id}" selected>${el.name}</option>`:`<option value="${el.id}">${el.name}</option>`;
					}else{
						html = `<option value="${el.id}">${el.name}</option>`;
					}
					$('#routeVillage').append(html);
				});
			});
			$('#routeStreet').change(function(event) {
				let id=$(this).val();
				Ajax("/xjrest/area/auth_area?areaType=2&townId="+id,function(data){
					$('#routeVillage').html('');
					let nodes = data.ret.value;
					$.each(nodes,function(index, el) {
						let html = `<option value="${el.id}">${el.name}</option>`;
						$('#routeVillage').append(html);
					});
				});
			});
			$('#showMap').click(function(event) {
				$('.routeMap').show();
				setPiont();
			});
			$('#closeInfo').click(function(event) {
				$('.layui-layer-shade').click();
			});
			$('label').click(function(event) {
				$('.typeImgOff').show();
				$('.typeImgOn').hide();
				$(this).find('.typeImgOff').hide();
				$(this).find('.typeImgOn').show();
			});
			layui.use('laydate', function(){
			    var laydate = layui.laydate;
			    laydate.render({
			        elem: '#buildTime',
			        type: 'year',
			        btns: ['confirm'],
			    });
			});
			if(type!=1){
				if(type==2){
					$('.infoHead .infoTitle').html('详情');
					$('.submit').hide();
					$('.mapButton').hide();
					$('.mapInput').css('width','3.9rem');
				}else{
					$('.infoHead .infoTitle').html('修改');
				}
				currentPoint=data.pointId;
				$('#equipmentType').val(data.equipmentType);
			}else{
				$('#buildTime').val(DateFormat('yyyy'));
			};
			checkBlur('.infoBody');
			$('#submit').click(function(event) {
				if(checkInput('.infoBody')==1){
                    layer.msg('请输入完整信息');
                    return;
                }
				let parms={};
				parms.pointAddress=_address;
				parms.pointName=$('#pointAddress').val();
				parms.useTime=$('#useTime').val();
				parms.buildTime=$('#buildTime').val();
				parms.equipmentType=$('#equipmentType').val();
				parms.townId=$('#routeStreet').val();
				parms.villageId=$('#routeVillage').val();
				parms.linkman=$('#linkman').val();
				parms.linkphone=$('#linkphone').val();
				parms.manufacturer=$('#manufacturer').val();
				parms.equipmentNum=$('#equipmentNum').val();
				parms.longitude=$('#lng').attr('lng');
				parms.latitude=$('#lng').attr('lat');
				parms.remark=$('#routeMsg').val();
				if($(this).val()=='确认添加'){
					Ajax("/xjrest/point/point_save",pointSaveBack,parms);
				}else{
					parms.pointId=currentPoint;
					Ajax("/xjrest/point/point_update",pointSaveBack,parms);
				}
				function pointSaveBack(data){
					if(data.ret.success){
						layer.closeAll();
						layer.msg('保存成功');
						searchRoute();
					}else{
						layer.msg('保存失败');
					}
				}
			});
		}
	}

	function upload(){
		var uploadEventFile = $("#excelFile").val();
	    if (uploadEventFile == '') {
	        layer.msg("请择excel,再上传");
	        return;
	    } else if (uploadEventFile.lastIndexOf(".xls") < 0) {
	        layer.msg("只能上传Excel文件");
	        return;
	    } else {
	    	layer.load(1);
	        var formData = new FormData();
			$("#fileName1").val(uploadEventFile);
	        formData.append('fileName',uploadEventFile);
			$('#forms').attr({"action":"/xjrest/point/point_import","method":"post","onsubmit":"return savePro()"}).submit();
	    }
	}

	window.savePro = function() { 
		$("#forms").ajaxSubmit(function(message) {
			let _msg = JSON.parse(message);
			if(_msg.ret.success){
				layer.closeAll();
				$("#excelFile").val('');
				$("#filePath").val('');
				reloadTable();
				layer.msg('导入成功');
			}else{
				$("#excelFile").val('');
				$("#filePath").val('');
				layer.closeAll();
				let html = '';
				let errMsg = _msg.ret.value;
				for (key in errMsg) {
					let str = `<div class='errLine'>${errMsg[key]}</div>`;
					html+=str;
				}
				let _html = `<div class="errBox">${html}</div>`
				layer.alert(_html, {
				  skin: 'layui-layer-lan' //样式类名
				  ,closeBtn: 0
				}, function(){
				  layer.closeAll();
				});
				$('.layui-layer-title').html('导入失败原因');
			}
		}); 
		return false;
	}

	function exportTable(){
		layer.confirm('确定导出表格？', {
		    btn: ['确定','取消']
		}, function(){
			$("#areaId").val(currentAreaId);
	        $("#areaType").val(currentAreaType);
	        $("#areaParm").val($("#searchBox").val());
		    let searchParam = $("#searchBox").val();
			console.log("/xjrest/point/point_export?areaId="+currentAreaId+"&areaType="+currentAreaType+"&searchParam="+searchParam)
			$('#forms').attr({"action":"/xjrest/point/point_export?areaId="+currentAreaId+"&areaType="+currentAreaType+"&searchParam="+searchParam,"method":"get","onsubmit":""}).submit();
			layer.closeAll();
		}, function(){

		});
	}

	/*window.exportPro = function(){
		$("#forms").ajaxSubmit(function(message){
			let _msg = JSON.parse(message);
			if(_msg.ret.success){
				layer.msg('导出成功');
			}else{
				layer.msg('暂无可导出数据');
			}
		})

		return false;
	}*/

	function searchRoute(){
		let parms = {};
		parms.areaId = currentAreaId;
		parms.areaType = currentAreaType;
		parms.searchParam = $('#searchBox').val();
		parms.status = $('#isEdited').val();
		reloadTable(parms);
	}

	function setPiont() {
		address.lng=$('#lng').attr('lng')==''?'118.904272':$('#lng').attr('lng');
		address.lat=$('#lng').attr('lat')==''?'32.076234':$('#lng').attr('lat');
	    var map = new BMap.Map("routeMap", { mapType: BMAP_SATELLITE_MAP });
	    var point = new BMap.Point(address.lng, address.lat);
	    var maker = new BMap.Marker(point);
	    map.addOverlay(maker);
	    map.centerAndZoom(point, 16);
	    var geocoder = new BMap.Geocoder();
	    geocoder.getLocation(point,function(rs){
	        _address = rs.surroundingPois.length == 0?rs.address : rs.surroundingPois[0].address;
	        var label = new BMap.Label(_address,{offset:new BMap.Size(20,-10)});
	        maker.setLabel(label);
	    });
	    map.enableScrollWheelZoom(true);
	    //选择坐标
	    map.addEventListener("click", function(e) {
	        map.clearOverlays();
	        address.lng = e.point.lng;
	        address.lat = e.point.lat;
	        point = new BMap.Point(address.lng, address.lat);
	        maker = new BMap.Marker(point);
	        map.addOverlay(maker);
	        geocoder.getLocation(e.point,function(rs){
	            _address = rs.surroundingPois.length == 0?rs.address : rs.surroundingPois[0].address;
	            var label = new BMap.Label(_address,{offset:new BMap.Size(20,-10)});
	            maker.setLabel(label);
	        });
	        map.panTo(point);
	    });
	    $('#searchMapButton').click(function(event) {
	        searchMap = $('#searchMap').val();
	        var local = new BMap.LocalSearch(map, {
	            renderOptions:{map: map}
	        });
	        local.search(searchMap);
	    });
	    $('#searchMap').bind('keypress', function (event) { 
	        if (event.keyCode == "13") { 
	            $("#searchMapButton").trigger('click');
	        }
	    });
	    $('.mapSet').click(function(event) {
	    	if($(this).attr('id')=='cancel'){
	    		$('.routeMap').hide();
	    	}else{
	    		$('#lng').attr('lng',address.lng);
				$('#lng').attr('lat',address.lat);
				$('#lng').val(address.lng+'/'+address.lat);
	    		$('.routeMap').hide();
	    	}
		});
	}
	
	function initBatchUpdate(){
		var checkedId = $('#gridRepairTable').datagrid('getChecked');
		
		if (null == checkedId || checkedId.length == 0) {
			layer.msg('请勾选要修改的信息！');
		}
		else {
			let _html = tpls.tplRouteBatch({message: checkedId});
			layer.open({
			  type: 1,
			  title: false,
			  closeBtn: 0,
			  shadeClose: true,
			  skin: 'routeOpen',
			  content: _html
			});
			$('#closeInfoUpdate').click(function(event) {
				$('.layui-layer-shade').click();
			});
			$('#submitUpdate').click(function(event) {
				if(checkInput('.infoBody')==1){
                    layer.msg('请输入完整信息');
                    return;
                }
				var manufacturer = $("#manufacturerUpdate").val();
				var useTime = $("#useTimeUpdate").val();
				var pointIds = [];
				$.each(checkedId, function(index, item){
					pointIds.push(item.pointId);
			    });
				$.ajax({
    	            url: '/xjrest/point/update/batch',
    	            type: "post",
    	            contentType: "application/json",
    	            data: JSON.stringify({
    	                "pointIds": pointIds,
    	                "manufacturer": manufacturer,
    	                "useTime": useTime
    	            }),
    	            success: function(result) {
    	            	result = eval("(" + result + ")");
    	            	if(result.ret.success){
    						layer.closeAll();
    						layer.msg('修改成功');
    						searchRoute();
    					}else{
    						layer.msg('修改失败');
    					}
    	            },
    	            error: function(result) {
    	            	
    	            }
    	        });
			});
		}
		
	}

	return _route;
})

